<template>
  <div class="mod-config">
    <el-form :inline="true"
             ref="dataForm"
             size="small"
             :model="dataForm"
             @keyup.enter.native="searchClickHandle()">
      <el-row>
        <el-col :span="24">
          <el-form-item prop="inputParam">
            <el-input placeholder="请输入内容"
                      v-model="inputParam"
                      class="input-with-select"
                      clearable>
              <el-select v-model="selectParam"
                         slot="prepend"
                         placeholder="请选择">
                <el-option v-for="item in selectOps.querys"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"></el-option>
              </el-select>
              <!-- <el-button slot="append"
                         icon="el-icon-search"
                         @click="getDataList()"></el-button> -->
            </el-input>
          </el-form-item>
          <el-form-item prop="districtArr">
            <el-cascader :options="districts"
                         :props="districtProps"
                         v-model="dataForm.districtArr"
                         placeholder="所在地区"
                         style="width: 15rem; margin: -6px 0;"
                         @change="handleChange"
                         clearable
                         class="el-cascader-menu__list"></el-cascader>

          </el-form-item>
          <el-form-item prop="sex">
            <el-select v-model="dataForm.sex"
                       placeholder="性别"
                       clearable>
              <el-option v-for="item in selectOps.sex"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="birthday">
            <el-date-picker v-model="dataForm.birthday"
                            type="date"
                            placeholder="生日"
                            style="width:150px;"></el-date-picker>
          </el-form-item>
          <el-form-item prop="cardTypeId">
            <el-select v-model="dataForm.cardTypeId"
                       placeholder="会员卡类型"
                       @change="cardTypeChangeHandle"
                       clearable
                       style="width: 10rem">
              <el-option v-for="item in selectOps.cardtyps"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="expdate">
            <el-date-picker v-model="dataForm.expdate"
                            type="datetime"
                            placeholder="截止日期"></el-date-picker>
          </el-form-item>
          <el-form-item prop="education">
            <el-select v-model="dataForm.education"
                       placeholder="学历"
                       @change="educationChangeHandle"
                       clearable
                       style="width: 10rem">
              <el-option v-for="item in selectOps.education"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="hometown">
            <el-select v-model="dataForm.hometown"
                       clearable
                       placeholder="籍贯">
              <el-option v-for="item in selectOps.hometown"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="marriage">
            <el-select v-model="dataForm.marriage"
                       clearable
                       placeholder="婚姻状况"
                       style="width:10rem">
              <el-option v-for="item in selectOps.marriage"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="orderby">
            <el-select v-model="dataForm.orderby"
                       clearable
                       placeholder="排序"
                       style="width:10rem">
              <el-option v-for="item in selectOps.orderby"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary"
                       icon="el-icon-search"
                       @click="searchClickHandle"
                       size="small">搜索</el-button>
            <el-button @click="resetForm"
                       size="small">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table ref="filterTable"
              :data="dataList"
              border
              stripe
              size="small"
              v-loading="dataListLoading"
              @selection-change="selectionChangeHandle"
              style="width: 100%;">
      <el-table-column prop="id"
                       header-align="center"
                       align="center"
                       label="#"
                       width="50">
      </el-table-column>
      <el-table-column prop="name"
                       header-align="center"
                       align="center"
                       width="100"
                       label="姓名">
        <template slot-scope="scope">
          {{scope.row.name || '-'}}
        </template>
      </el-table-column>

      <el-table-column prop="sex"
                       header-align="center"
                       align="center"
                       label="性别"
                       width="60">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex == 1">男</el-tag>
          <el-tag v-else-if="scope.row.sex == 0"
                  type="success">女</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cardNumber"
                       header-align="center"
                       align="center"
                       width="100"
                       label="会员卡号">
        <template slot-scope="scope">
          {{scope.row.cardNumber || '-'}}
        </template>
      </el-table-column>
      <el-table-column prop="cardTypeName"
                       header-align="center"
                       align="center"
                       width="140"
                       label="会员类型">
        <template slot-scope="scope">
          {{scope.row.cardTypeName || '-'}}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="usage"
                       header-align="center"
                       align="center"
                       width="80"
                       label="可用次数"></el-table-column> -->
      <el-table-column prop="createdTime"
                       header-align="center"
                       align="center"
                       label="加入时间"
                       width="155">
        <template slot-scope="scope">
          <span>{{scope.row.createdTime | formatDate('yyyy-MM-dd hh:mm:ss')}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="createdTimeByCard"
                       header-align="center"
                       align="center"
                       label="办卡时间"
                       width="155">
        <template slot-scope="scope">
          <span v-if="scope.row.createdTimeByCard">{{scope.row.createdTimeByCard | formatDate('yyyy-MM-dd hh:mm:ss')}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center"
                       align="center"
                       width="155"
                       label="有效日期">
        <template slot-scope="scope">
          <span v-if="scope.row.expDate">{{scope.row.expDate | formatDate('yyyy-MM-dd hh:mm:ss')}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center"
                       align="center"
                       width="90"
                       label="座位号">
        <template slot-scope="scope">
          {{scope.row.seat || '-'}}
        </template>
      </el-table-column>

      <el-table-column header-align="center"
                       align="center"
                       width="95"
                       label="出生日期">
        <template slot-scope="scope">
          <span>{{scope.row.birthday | formatDate}}</span>
        </template>
      </el-table-column>

      <el-table-column prop="telphone"
                       header-align="center"
                       align="center"
                       width="110"
                       label="联系电话">
      </el-table-column>

      <el-table-column header-align="center"
                       align="center"
                       label="地区"
                       min-width="200">
        <template slot-scope="scope">
          <span>{{scope.row.provincename}}/{{scope.row.cityname}}/{{scope.row.areaname}}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right"
                       header-align="center"
                       align="center"
                       width="222"
                       label="操作">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row.id)"
                     size="mini">详情</el-button>
          <!-- <el-button v-if="!scope.row.cardNumber"
                     size="mini">新增会员卡</el-button> -->
          <el-button type="danger"
                     size="mini"
                     @click="addOrUpdateHandle(scope.row.id)"
                     v-if="isAuth('member:member:edit')">编辑</el-button>
          <el-button type="danger"
                     size="mini"
                     @click="deleteHandle(scope.row.id)"
                     v-if="isAuth('member:member:edit')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle"
                   @current-change="currentChangeHandle"
                   :current-page="pageIndex"
                   :page-sizes="[10, 20, 50, 100]"
                   :page-size="pageSize"
                   :total="totalPage"
                   background
                   layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible"
                   ref="addOrUpdate"
                   @refreshDataList="getDataList"></add-or-update>
  </div>
</template>

<script>
import { formatDate } from '@/utils/date'
import AddOrUpdate from './member-add-or-update'

export default {
  filters: {
    formatDate (time, format = 'yyyy-MM-dd') {
      var date = new Date(time * 1000)
      return formatDate(date, format)
    }
  },
  data () {
    return {
      inputParam: '',
      selectParam: 'name',
      china: {
        province: [], // 省份
        city: [], // 城市
        area: [] // 区县
      },
      selectOps: {
        // 性别数组
        sex: [
          { id: 1, name: '男' },
          { id: 0, name: '女' }
        ],
        // 指定的搜索字段数据
        querys: [
          { id: 'name', name: '会员姓名' },
          { id: 'address', name: '居住地址' },
          { id: 'hobby', name: '兴趣爱好' },
          { id: 'health', name: '健康状况' }
        ],
        // 学历
        education: [
          { id: 1, name: '文盲' },
          { id: 2, name: '小学' },
          { id: 3, name: '初中' },
          { id: 4, name: '高中/技校/中专' },
          { id: 5, name: '大学专科以上' },
          { id: 6, name: '不详' }
        ],
        // 婚姻状况
        marriage: [
          { id: 1, name: '未婚' },
          { id: 2, name: '已婚' },
          { id: 3, name: '丧偶' },
          { id: 4, name: '离婚' },
          { id: 5, name: '未说明的婚姻状况' }
        ],
        // 籍贯
        hometown: [
          { id: 1, name: '汉族' },
          { id: 2, name: '少数民族' }
        ],
        cardtyps: [],  // 会员卡类型
        orderby: [
          { id: 'cardNumberDesc', name: '会员卡号(降序)' }
        ]
      },
      dataForm: {
        name: '',
        sex: '',
        birthday: '',
        provincecode: '',
        citycode: '',
        areacode: '',
        // 地区级连选择数组
        districtArr: [],
        cardTypeId: '', // 会员类型
        education: '', //  学历
        marriage: '', // 婚姻状况
        hometown: '', // 籍贯
        expdate: '', // 会员到期时间
        orderby: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      // value: [],
      districts: [],  // 地区数组
      // 级连下拉框可选项设置
      districtProps: {
        label: 'name',  // 显示的值
        value: 'code',  // 选择的值
        children: 'children'  // 子节点
      }

    }
  },
  components: {
    AddOrUpdate
  },
  watch: {
    select (newVal, oldVal) {
      // console.log(`select.new:${newVal}, select.old:${oldVal}`)
    }
  },
  activated () {
    // 获取会员列表数据
    this.getDataList()
    // this.getProvice()
    // 获取地区数据
    this.getDistricts()
    // 获取会员卡类型数据
    this.getCardType()
  },
  methods: {
    // 日期格式化
    time (time = +new Date()) {
      var date = new Date(time + 8 * 3600)
      return date.toJSON().substr(0, 19).replace('T', ' ')
    },
    // 不足指定位数，后面补零
    pad (num, n) {
      var tbl = []
      var len = n - num.toString().length
      if (len <= 0) return num
      if (!tbl[len]) tbl[len] = (new Array(len + 1)).join('0')
      return num + tbl[len]
    },
    // 获取省份数据
    getProvice () {
      this.$http({
        url: this.$http.adornUrl(`/member/cnprovince/list`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.china.province = data.page.list
        }
      })
    },
    // 获取城市数据
    getCity (code, target = 1) {
      this.dataForm.provincename = this.china.province.find((item) => {
        return item.code === code
      }).name
      if (target === 1) {
        this.dataForm.citycode = ''
        this.china.city = []

        this.dataForm.areacode = ''
        this.china.area = []
      }
      this.$http({
        url: this.$http.adornUrl(`/member/cncity/province/${code}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.china.city = data.data
          // console.log(this.china.city)
        }
      })
    },
    // 获取区域数据
    getArea (code, target = 1) {
      this.dataForm.cityname = this.china.city.find((item) => {
        return item.code === code
      }).name
      if (target === 1) {
        this.dataForm.areacode = ''
        this.china.area = []
      }
      this.$http({
        url: this.$http.adornUrl(`/member/cnarea/city/${code}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.china.area = data.data
        }
      })
    },
    areaChange (code) {
      this.dataForm.areaname = this.china.area.find((item) => {
        return item.code === code
      }).name
    },
    // 获取地区数据
    getDistricts () {
      this.$http({
        url: this.$http.adornUrl(`/member/cnprovince/districts`),
        method: 'get'
      }).then(({ data }) => {
        if (data.code === 0) {
          this.districts = data.data.districts
        }
      })
    },
    // 获取会员卡类型
    getCardType () {
      this.$http({
        url: this.$http.adornUrl(`/member/cardtype/list`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.selectOps.cardtyps = data.page.list
        }
      })
    },
    // 会员卡类型选中值发生改变时触发
    cardTypeChangeHandle (id) {
      // console.log(this.dataForm.cardTypeId)
    },
    // 地区级连发生改变时调用
    handleChange () {
      // console.log(this.dataForm.districtArr)
    },
    // 学历选中值发生改变时触发
    educationChangeHandle () {
      // console.log(this.dataForm.education)
    },
    resetForm () {
      if (this.$refs['dataForm'] !== undefined) {
        this.inputParam = ''
        this.$refs['dataForm'].resetFields()
      }
    },
    filterHandler (value, row, column) {
      const property = column['property']
      // console.log('property=' + property)
      // console.log(row[property])
      // console.log('value=' + value)
      return row[property] === value
      // console.log(value)
      // console.log(row)
      // console.log(column)
    },
    searchClickHandle () {
      this.pageIndex = 1
      this.getDataList()
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      // let opt = this.selectParam
      let params = {
        'page': this.pageIndex,
        'limit': this.pageSize,
        // 'name': this.dataForm.name,
        'sex': this.dataForm.sex,
        'birthday': this.dataForm.birthday ? this.dataForm.birthday.getTime() / 1000 : '',
        'provincecode': this.dataForm.districtArr.length === 3 ? this.pad(this.dataForm.districtArr[0], 6) : '',
        'citycode': this.dataForm.districtArr.length === 3 ? this.pad(this.dataForm.districtArr[1], 6) : '',
        'areacode': this.dataForm.districtArr.length === 3 ? this.pad(this.dataForm.districtArr[2], 6) : '',
        'cardTypeId': this.dataForm.cardTypeId,
        'education': this.dataForm.education,
        'marriage': this.dataForm.marriage,
        'hometown': this.dataForm.hometown,
        'expdate': this.dataForm.expdate ? this.dataForm.expdate.getTime() / 1000 : '',
        'orderby': this.dataForm.orderby
      }
      if (this.selectParam) {
        params[this.selectParam] = this.inputParam
        // console.log(params)
      }
      this.$http({
        url: this.$http.adornUrl('/member/member/list'),
        method: 'get',
        params: this.$http.adornParams(params)
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    handleClick (id) {
      this.$router.push({
        name: 'member-info',
        params: { id: id }
      })
    },
    // 删除
    deleteHandle (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/member/member/delete'),
          method: 'post',
          data: this.$http.adornData(id, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.getDataList()
              }
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      })
    }
  }
}
</script>
<style scoped>
.el-select {
  width: 105px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.el-form-item__content .el-input-group,
.el-form-item__label,
.el-tag .el-icon-close {
  vertical-align: unset;
}
</style>